#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
*** BackTwit ***
Small twitter daemon.
:
Copyright 2008 Pavel Klinkov
15.12.2008

"""
import datetime
import getpass
from urllib2 import URLError
import notifier
import config

try:
    import time
except ImportError :
    print "Install Python-Time"
    exit(1) 
    
try:
    import twitter
except ImportError :
    print "Install Pyhton-Twitter from: http://code.google.com/p/python-twitter/"
    exit(1)

def ts():
    q = datetime.datetime.now().timetuple()
    return str(q.tm_year) + '-' + str(q.tm_mon) + '-' + str(q.tm_mday) + ' ' + str(q.tm_hour) + ':' + str(q.tm_sec)

def url_opener(id, action_key):
    print "url_opener"

def main():
    print "Twitter Daemon Start"
    try:
	cfg = config.Config()
        twit = twitter.Api(cfg.usr, cfg.password)
	messenger  = notifier.Notifier(cfg.show_time,cfg.debug, url_opener)
        while (1):
            print ts() + ": Cycle"
            try:
                statuses = twit.GetFriendsTimeline(user=cfg.usr,since_id=cfg.last_id, count= cfg.count)
                for i in statuses:
                    messenger.send("Twit: " + i.user.name + "(" + i.GetRelativeCreatedAt() + ")", i.text)
                    cfg.last_id = max(cfg.last_id, i.id)
            except URLError, e:
                    if hasattr(e, 'reason'):
                        print ts() + 'Connection failed: ' +  e.reason
                    elif hasattr(e, 'code'):
                        print ts() + 'The server Error code: ' + e.code
            time.sleep(cfg.cycle_time)
            
    except KeyboardInterrupt:
        if (cfg.debug) : print "Stop Time : " + ts()
        exit(0)

if __name__ == "__main__":
    main()
